package crawler.extension.ocr.tool;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import crawler.extension.ocr.configure.LocalConfigure;
import crawler.utility.file.FileOperation;

@Component
public class PathTool {

	private LocalConfigure localConfigure;

	private static final String OCR_PATH = "ocr";
	private static final String OCR_DEFAULT = OCR_PATH + "/default";

	private String path;
	private String filePath;
	private String configureWebsite;
	private String tessdataPathDefault;

	@Autowired
	public PathTool(LocalConfigure localConfigure) {
		this.localConfigure = localConfigure;
		
		this.filePath = localConfigure.getOcrFilepath();
		this.configureWebsite = localConfigure.getOcrWebsite();
		
		this.path =  this.getClass().getResource("/").getPath();
		this.tessdataPathDefault = this.path + OCR_DEFAULT;
	}

	public Map<String, String> selectConfig(String website) {
		
		String defaultTessdata = tessdataPathDefault.substring(1);
		String defaultFilePath = filePath;

		String keyFilePath = "filePath";
		String keyTessdata = "tessdata";

		Map<String, String> configMap = new HashMap<String, String>();
		configMap.put(keyFilePath, defaultFilePath);
		configMap.put(keyTessdata, defaultTessdata);

		if (website == null || "".equals(website)) {
			return configMap;
		}

		String[] websites = configureWebsite.split(",");
		for (int i = 0; i < websites.length; i++) {
			String eachWebsite = websites[i];
			if (eachWebsite.equals(website)) {
				String websiteFilePath = filePath + "/" + eachWebsite + "/";
				String webstieOCRPath = OCR_PATH + "/" + eachWebsite;

				FileOperation fileOperation = new FileOperation(webstieOCRPath + "/" + keyTessdata);

				configMap.put(keyFilePath, websiteFilePath);
				if (fileOperation.exists()) {
					configMap.put(keyTessdata, webstieOCRPath);
				} else {
					configMap.put(keyTessdata, defaultTessdata);
				}

				break;
			}
		}

		return configMap;
	}
}
